Deprecated. Use HandlerFor directly
Moduleyesod-core-1.6.26.0Haskell2010
Yesod.Core.Handler
- 9 types
- 1 class
- 120 values
- Packageyesod-core-1.6.26.0
- Exports130
- LanguageHaskell2010
- LicenceMIT
- SourceTypes.hs
Handler monad
2 declarationsA generic handler monad, which can have a different subsite and master site. We define a newtype for better error message.
Instances15Monad, Functor, Applicative, MonadIO, MonadThrow, PrimMonad, …
Monad (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesFunctor (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesApplicative (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadIO (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadThrow (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesPrimMonad (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadUnliftIO (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadResource (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadLogger (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadLoggerIO (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadHandler (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadReader (HandlerData site site) (HandlerFor site)Defined in yesod-core-1.6.26.0 · Yesod.Core.Typestype PrimState (HandlerFor site) = PrimState IODefined in yesod-core-1.6.26.0 · Yesod.Core.Typestype HandlerSite (HandlerFor site) = siteDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (HandlerFor site) = siteDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handler
Read information from handler
Get the master site application argument.
Get a specific component of the master site application argument.
Analogous to the gets function for operating on StateT.
Get the URL rendering function.
The URL rendering function with query-string parameters.
Get all the post parameters passed to the handler. To also get the submitted files (if any), you have to use runRequestBody instead of this function.
Get the route requested by the user. If this is a 404 response- where the user requested an invalid route- this function will return Nothing.
Get the request's Request value.
Stream in the raw request body without any parsing.
Request information
Request datatype
A tuple containing both the POST parameters and submitted files.
The parsed request information. This type augments the standard WAI Request with additional information.
Constructors
YesodRequestreqGetParams :: ![(Text, Text)]Same as queryString, but decoded to
Text.reqCookies :: ![(Text, Text)]reqWaiRequest :: !RequestreqLangs :: ![Text]Languages which the client supports. This is an ordered list by preference.
reqToken :: !Maybe TextA random, session-specific token used to prevent CSRF attacks.
reqSession :: !SessionMapInitial session sent from the client.
Since 1.2.0
reqAccept :: ![ContentType]An ordered list of the accepted content types.
Since 1.2.0
Stream the data from the file. Since Yesod 1.2, this has been generalized
to work in any MonadResource.
Extract a strict ByteString body from a FileInfo.
This function will block while reading the file.
do
fileByteString <- fileSourceByteString fileInfoConvenience functions
Get the list of supported languages supplied by the user.
Languages are determined based on the following (in descending order of preference):
The _LANG get parameter.
The _LANG user session variable.
The _LANG cookie.
Accept-Language HTTP header.
Yesod will seek the first language from the returned list matched with languages supporting by your application. This language will be used to render i18n templates. If a matching language is not found the default language will be used.
This is handled by parseWaiRequest (not exposed).
NOTE: Before version 1.6.19.0, this function prioritized the session
variable above all other sources.
Lookup parameters
Lookup for GET parameters.
Lookup for cookie data.
Lookup for POSTed files.
Lookup a request header.
Lookup authentication data
Lookup basic authentication data from Authorization header of request. Returns user name and password
Lookup bearer authentication datafrom Authorization header of request. Returns bearer token value
Multi-lookup
Lookup for GET parameters.
Lookup for POST parameters.
Lookup for cookie data.
Lookup for POSTed files.
Lookup a request header.
Responses
0 declarationsPure
Provide a pure value for the response body.
respond ct = return . TypedContent ct . toContentStreaming
Use a Source for the response body.
Note that, for ease of use, the underlying monad is a HandlerFor. This
implies that you can run any HandlerFor action. However, since a streaming
response occurs after the response headers have already been sent, some
actions make no sense here. For example: short-circuit responses, setting
headers, changing status codes, etc.
In a streaming response, send a single chunk of data. This function works
on most datatypes, such as ByteString and Html.
In a streaming response, send a flush command, causing all buffered data to be immediately sent to the client.
Type-specialized version of sendChunk for strict ByteStrings.
Type-specialized version of sendChunk for lazy ByteStrings.
Type-specialized version of sendChunk for strict Texts.
Type-specialized version of sendChunk for lazy Texts.
Type-specialized version of sendChunk for Htmls.
Redirecting
Some value which can be turned into a URL for redirects.
Methods
toTextUrl :: (MonadHandler m, HandlerSite m ~ master) => a -> m TextConverts the value to the URL and a list of query-string parameters.
Instances6RedirectUrl
RedirectUrl master StringDefined in yesod-core-1.6.26.0 · Yesod.Core.HandlerRedirectUrl master TextDefined in yesod-core-1.6.26.0 · Yesod.Core.HandlerRedirectUrl master (Route master)Defined in yesod-core-1.6.26.0 · Yesod.Core.Handler(RedirectUrl master a, PathPiece b) => RedirectUrl master (Fragment a b)Defined in yesod-core-1.6.26.0 · Yesod.Core.Handler(key ~ Text, val ~ Text) => RedirectUrl master (Route master, Map key val)Defined in yesod-core-1.6.26.0 · Yesod.Core.Handler(key ~ Text, val ~ Text) => RedirectUrl master (Route master, [(key, val)])Defined in yesod-core-1.6.26.0 · Yesod.Core.Handler
Redirect to the given route. HTTP status code 303 for HTTP 1.1 clients and 302 for HTTP 1.0 This is the appropriate choice for a get-following-post technique, which should be the usual use case.
If you want direct control of the final status code, or need a different status code, please use redirectWith.
Redirect to the given URL with the specified status code.
Redirect to a POST resource.
This is not technically a redirect; instead, it returns an HTML page with a POST form, and some Javascript to automatically submit the form. This can be useful when you need to post a plain link somewhere that needs to cause changes on the server.
Add a fragment identifier to a route to be used when redirecting. For example:
redirect (NewsfeedR :#: storyId)@since 1.2.9.
Constructors
a :#: b
Instances2RedirectUrl, Show
(RedirectUrl master a, PathPiece b) => RedirectUrl master (Fragment a b)Defined in yesod-core-1.6.26.0 · Yesod.Core.Handler(Show a, Show b) => Show (Fragment a b)Defined in yesod-core-1.6.26.0 · Yesod.Core.Handler
Errors
Return a 404 not found page. Also denotes no handler available.
Return a 405 method not supported page.
Return a 401 status code
Return a 403 permission denied page.
Return a 403 permission denied page.
Return a 400 invalid arguments page.
Return a 400 invalid arguments page.
Short-circuit responses
Note that since short-circuiting is implemented by using exceptions, using e.g. sendStatusJSON inside a runDB block will result in the database actions getting rolled back:
runDB $ do
userId <- insert $ User "username" "email@example.com"
postId <- insert $ BlogPost "title" "hi there!"
The previous two inserts will be rolled back.
sendStatusJSON Status.status200 ()
Bypass remaining handler code and output the given file.
For some backends, this is more efficient than reading in the file to memory, since they can optimize file sending via a system call to sendfile.
Same as sendFile, but only sends part of a file.
Bypass remaining handler code and output the given content with a 200 status code.
Bypass remaining handler code and output the given content with the given status code.
Type specific response with custom status
Bypass remaining handler code and output the given JSON with the given status code.
Send a 201 Created response with the given route as the Location
response header.
Bypass remaining handler code and output no content with a 204 status code.
Send a Response. Please note: this function is rarely necessary, and will disregard any changes to response headers and session that you have already specified. This function short-circuits. It should be considered only for very specific needs. If you are not sure if you need it, you don't.
Switch over to handling the current request with a WAI Application.
Send a raw response. This is used for cases such as WebSockets. Requires WAI 2.1 or later, and a web server which supports raw responses (e.g., Warp).
Send a raw response without conduit. This is used for cases such as WebSockets. Requires WAI 3.0 or later, and a web server which supports raw responses (e.g., Warp).
Send a 304 not modified response immediately. This is a short-circuiting action.
Different representations
4 declarationsHTTP allows content negotation to determine what representation of data you would like to use. The most common example of this is providing both a user-facing HTML page and an API facing JSON response from the same URL. The means of achieving this is the Accept HTTP header, which provides a list of content types the client will accept, sorted by preference.
By using selectRep and provideRep, you can provide a number of different representations, e.g.:
selectRep $ do
provideRep produceHtmlOutput
provideRep produceJsonOutputThe first provided representation will be used if no matches are found.
Select a representation to send to the client based on the representations provided inside this do-block. Should be used together with provideRep.
Provide a single representation to be used, based on the request of the client. Should be used together with selectRep.
Same as provideRep, but instead of determining the content type from the type of the value itself, you provide the content type separately. This can be a convenience instead of creating newtype wrappers for uncommonly used content types.
provideRepType "application/x-special-format" "This is the content"Internal representation of a single provided representation.
Setting headers
8 declarationsSet the cookie on the client.
Helper function for setCookieExpires value
Unset the cookie on the client.
Note: although the value used for key and path is Text, you should only use ASCII values to be HTTP compliant.
Set an arbitrary response header.
Note that, while the data type used here is Text, you must provide only ASCII value to be HTTP compliant.
Deprecated. Please use addHeader instead
Deprecated synonym for addHeader.
Replace an existing header with a new value or add a new header if not present.
Note that, while the data type used here is Text, you must provide only ASCII value to be HTTP compliant.
Set the language in the user session. Will show up in languages on the next request.
Content caching and expiration
Set the Cache-Control header to indicate this response should be cached for the given number of seconds.
Set the Expires header to some date in 2037. In other words, this content is never (realistically) expired.
Set an Expires header in the past, meaning this content should not be cached.
Set an Expires header to the given date.
Check the if-none-match header and, if it matches the given value, return a 304 not modified response. Otherwise, set the etag header to the given value.
Note that it is the responsibility of the caller to ensure that the provided value is a valid etag value, no sanity checking is performed by this function.
Check the if-none-match header and, if it matches the given value, return a 304 not modified response. Otherwise, set the etag header to the given value.
A weak etag is only expected to be semantically identical to the prior content, but doesn't have to be byte-for-byte identical. Therefore it can be useful for dynamically generated content that may be difficult to perform bytewise hashing upon.
Note that it is the responsibility of the caller to ensure that the provided value is a valid etag value, no sanity checking is performed by this function.
Session
8 declarationsLookup for session data.
Lookup for session data in binary format.
Get all session variables.
Set a variable in the user's session.
The session is handled by the clientsession package: it sets an encrypted and hashed cookie on the client. This ensures that all data is secure and not tampered with.
Same as setSession, but uses binary data for the value.
Unsets a session variable. See setSession.
Clear all session variables.
@since: 1.0.1
Ultimate destination
Sets the ultimate destination variable to the given route.
An ultimate destination is stored in the user session and can be loaded later by redirectUltDest.
Same as setUltDest, but uses the current page.
If this is a 404 handler, there is no current page, and then this call does nothing.
Sets the ultimate destination to the referer request header, if present.
This function will not overwrite an existing ultdest.
redirectUltDest :: (RedirectUrl (HandlerSite m) url, MonadHandler m)=> urldefault destination if nothing in session
-> m a
Redirect to the ultimate destination in the user's session. Clear the value from the session.
The ultimate destination is set with setUltDest.
This function uses redirect, and thus will perform a temporary redirect to a GET request.
Remove a previously set ultimate destination. See setUltDest.
Messages
Adds a status and message in the user's session.
See getMessages.
Adds a message in the user's session but uses RenderMessage to allow for i18n
See getMessages.
Gets all messages in the user's session, and then clears the variable.
See addMessage.
Calls addMessage with an empty status
Calls addMessageI with an empty status
Gets just the last message in the user's session, discards the rest and the status
Subsites
4 declarationsA handler monad for subsite
Instances13Monad, Functor, Applicative, MonadIO, MonadThrow, MonadUnliftIO, …
Monad (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesFunctor (SubHandlerFor sub master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesApplicative (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadIO (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadThrow (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadUnliftIO (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadResource (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadLogger (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadLoggerIO (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.TypesMonadHandler (SubHandlerFor sub master)Defined in yesod-core-1.6.26.0 · Yesod.Core.Class.HandlerMonadReader (HandlerData child master) (SubHandlerFor child master)Defined in yesod-core-1.6.26.0 · Yesod.Core.Typestype HandlerSite (SubHandlerFor sub master) = masterDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handlertype SubHandlerSite (SubHandlerFor sub master) = subDefined in yesod-core-1.6.26.0 · Yesod.Core.Class.Handler
Helpers for specific content
0 declarationsHamlet
Deprecated. Use withUrlRenderer instead
Deprecated synonym for withUrlRenderer.
Provide a URL rendering function to the given function and return the result. Useful for processing Shakespearean templates.
Misc
Get a unique identifier.
Lifting
2 declarationsReturns a function that runs HandlerFor actions inside IO.
Sometimes you want to run an inner HandlerFor action outside the control flow of an HTTP request (on the outer HandlerFor action). For example, you may want to spawn a new thread:
getFooR :: Handler RepHtml
getFooR = do
runInnerHandler <- handlerToIO
liftIO $ forkIO $ runInnerHandler $ do
Code here runs inside HandlerFor but on a new thread.
This is the inner HandlerFor.
...
Code here runs inside the request's control flow.
This is the outer HandlerFor.
...
Another use case for this function is creating a stream of
server-sent events using HandlerFor actions (see
yesod-eventsource).
Most of the environment from the outer HandlerFor is preserved on the inner HandlerFor, however:
The request body is cleared (otherwise it would be very difficult to prevent huge memory leaks).
The cache is cleared (see cached).
Changes to the response made inside the inner HandlerFor are
ignored (e.g., session variables, cookies, response headers).
This allows the inner HandlerFor to outlive the outer
HandlerFor (e.g., on the forkIO example above, a response
may be sent to the client without killing the new thread).
forkHandler :: (SomeException -> HandlerFor site ())error handler
-> HandlerFor site ()-> HandlerFor site ()
forkIO for a Handler (run an action in the background)
Uses handlerToIO, liftResourceT, and resourceForkIO for correctness and efficiency
i18n
1 declarationgetMessageRender :: (MonadHandler m, RenderMessage (HandlerSite m) message) => m (message -> Text)Per-request caching
6 declarationsUse a per-request cache to avoid performing the same action multiple times. Values are stored by their type, the result of typeOf from Typeable. Therefore, you should use different newtype wrappers at each cache site.
For example, yesod-auth uses an un-exported newtype, CachedMaybeAuth and exports functions that utilize it such as maybeAuth. This means that another module can create its own newtype wrapper to cache the same type from a different action without any cache conflicts.
See the original announcement: http://www.yesodweb.com/blog/2013/03/yesod-1-2-cleaner-internals
Retrieves a value from the cache used by cached.
Sets a value in the cache used by cached.
a per-request cache. just like cached. cached can only cache a single value per type. cachedBy stores multiple values per type by usage of a ByteString key
cached is ideal to cache an action that has only one value of a type, such as the session's current user cachedBy is required if the action has parameters and can return multiple values per type. You can turn those parameters into a ByteString cache key. For example, caching a lookup of a Link by a token where multiple token lookups might be performed.
Retrieves a value from the cache used by cachedBy.
Sets a value in the cache used by cachedBy.
AJAX CSRF protection
0 declarationsWhen a user has authenticated with your site, all requests made from the browser to your server will include the session information that you use to verify that the user is logged in. Unfortunately, this allows attackers to make unwanted requests on behalf of the user by e.g. submitting an HTTP request to your site when the user visits theirs. This is known as a Cross Site Request Forgery (CSRF) attack.
To combat this attack, you need a way to verify that the request is valid. This is achieved by generating a random string ("token"), storing it in your encrypted session so that the server can look it up (see reqToken), and adding the token to HTTP requests made to your server. When a request comes in, the token in the request is compared to the one from the encrypted session. If they match, you can be sure the request is valid.
Yesod implements this behavior in two ways:
The yesod-form package stores the CSRF token in a hidden field in the form, then validates it with functions like
Yesod.Form.Functions.runFormPost.Yesod can store the CSRF token in a cookie which is accessible by Javascript. Requests made by Javascript can lookup this cookie and add it as a header to requests. The server then checks the token in the header against the one in the encrypted session.
The form-based approach has the advantage of working for users with Javascript disabled, while adding the token to the headers with Javascript allows things like submitting JSON or binary data in AJAX requests. Yesod supports checking for a CSRF token in either the POST parameters of the form (checkCsrfParamNamed), the headers (checkCsrfHeaderNamed), or both options (checkCsrfHeaderOrParam).
The easiest way to check both sources is to add the defaultCsrfMiddleware to your Yesod Middleware.
Opting-out of CSRF checking for specific routes
(Note: this code is generic to opting out of any Yesod middleware)
yesodMiddleware app = do
maybeRoute <- getCurrentRoute
let dontCheckCsrf = case maybeRoute of
Just HomeR -> True -- Don't check HomeR
Nothing -> True -- Don't check for 404s
_ -> False -- Check other routes
defaultYesodMiddleware $ defaultCsrfSetCookieMiddleware $ (if dontCheckCsrf then id else defaultCsrfCheckMiddleware) $ app
This can also be implemented using the csrfCheckMiddleware function.
Setting CSRF Cookies
Sets a cookie with a CSRF token, using defaultCsrfCookieName for the cookie name.
The cookie's path is set to /, making it valid for your whole website.
Takes a SetCookie and overrides its value with a CSRF token, then sets the cookie.
Make sure to set the setCookiePath to the root path of your application, otherwise you'll generate a new CSRF token for every path of your app. If your app is run from from e.g. www.example.com/app1, use app1. The vast majority of sites will just use /.
The default cookie name for the CSRF token ("XSRF-TOKEN").
Looking up CSRF Headers
Takes a header name to lookup a CSRF token. If the value doesn't match the token stored in the session, this function throws a PermissionDenied error.
Takes a header name to lookup a CSRF token, and returns whether the value matches the token stored in the session.
The default header name for the CSRF token ("X-XSRF-TOKEN").
Looking up CSRF POST Parameters
Takes a POST parameter name to lookup a CSRF token, and returns whether the value matches the token stored in the session.
Takes a POST parameter name to lookup a CSRF token. If the value doesn't match the token stored in the session, this function throws a PermissionDenied error.
The default parameter name for the CSRF token ("_token")
Checking CSRF Headers or POST Parameters
checkCsrfHeaderOrParam :: (MonadHandler m, MonadLogger m)=> CI ByteStringThe header name to lookup the CSRF token
-> TextThe POST parameter name to lookup the CSRF token
-> m ()
Checks that a valid CSRF token is present in either the request headers or POST parameters. If the value doesn't match the token stored in the session, this function throws a PermissionDenied error.