Blog: i18n, authentication, authorization, and database

This is a simple blog app. It allows an admin to add blog posts via a rich text editor (nicedit), allows logged-in users to comment, and has full i18n support. It is also a good example of using a Persistent database, leveraging Yesod’s authorization system, and templates.

While in general we recommend placing templates, Persist entity definitions, and routing in separate files, we’ll keep it all in one file here for convenience. The one exception you’ll see below will be i18n messages.

We’ll start off with our language extensions. In scaffolded code, the language extensions are specified in the cabal file, so you won’t need to put this in your individual Haskell files.

  1. {-# LANGUAGE OverloadedStrings, TypeFamilies, QuasiQuotes,
  2. TemplateHaskell, GADTs, FlexibleContexts,
  3. MultiParamTypeClasses, DeriveDataTypeable,
  4. GeneralizedNewtypeDeriving, ViewPatterns #-}

Now our imports.

  1. import Yesod
  2. import Yesod.Auth
  3. import Yesod.Form.Nic (YesodNic, nicHtmlField)
  4. import Yesod.Auth.OpenId (IdentifierType(..), authOpenId)
  5. import Data.Text (Text)
  6. import Network.HTTP.Client.TLS (tlsManagerSettings)
  7. import Network.HTTP.Conduit (Manager, newManager)
  8. import Database.Persist.Sqlite
  9. ( ConnectionPool, SqlBackend, runSqlPool, runMigration
  10. , createSqlitePool, runSqlPersistMPool
  11. )
  12. import Data.Time (UTCTime, getCurrentTime)
  13. import Control.Applicative ((<$>), (<*>), pure)
  14. import Data.Typeable (Typeable)
  15. import Control.Monad.Logger (runStdoutLoggingT)

First we’ll set up our Persistent entities. We’re going to both create our data types (via mkPersist) and create a migration function, which will automatically create and update our SQL schema. If you were using the MongoDB backend, migration would not be needed.

  1. share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|

Keeps track of users. In a more robust application, we would also keep account creation date, display name, etc.

  1. User
  2. email Text
  3. UniqueUser email

In order to work with yesod-auth’s caching, our User type must be an instance of Typeable.

  1. deriving Typeable

An individual blog entry (I’ve avoided using the word “post” due to the confusion with the request method POST).

  1. Entry
  2. title Text
  3. posted UTCTime
  4. content Html

And a comment on the blog post.

  1. Comment
  2. entry EntryId
  3. posted UTCTime
  4. user UserId
  5. name Text
  6. text Textarea
  7. |]

Every site has a foundation datatype. This value is initialized before launching your application, and is available throughout. We’ll store a database connection pool and HTTP connection manager in ours. See the very end of this file for how those are initialized.

  1. data Blog = Blog
  2. { connPool :: ConnectionPool
  3. , httpManager :: Manager
  4. }

To make i18n easy and translator friendly, we have a special file format for translated messages. There is a single file for each language, and each file is named based on the language code (e.g., en, es, de-DE) and placed in that folder. We also specify the main language file (here, “en”) as a default language.

  1. mkMessage "Blog" "blog-messages" "en"

Our blog-messages/en.msg file contains the following content:

  1. -- @blog-messages/en.msg
  2. NotAnAdmin: You must be an administrator to access this page.
  3. WelcomeHomepage: Welcome to the homepage
  4. SeeArchive: See the archive
  5. NoEntries: There are no entries in the blog
  6. LoginToPost: Admins can login to post
  7. NewEntry: Post to blog
  8. NewEntryTitle: Title
  9. NewEntryContent: Content
  10. PleaseCorrectEntry: Your submitted entry had some errors, please correct and try again.
  11. EntryCreated title@Text: Your new blog post, #{title}, has been created
  12. EntryTitle title@Text: Blog post: #{title}
  13. CommentsHeading: Comments
  14. NoComments: There are no comments
  15. AddCommentHeading: Add a Comment
  16. LoginToComment: You must be logged in to comment
  17. AddCommentButton: Add comment
  18. CommentName: Your display name
  19. CommentText: Comment
  20. CommentAdded: Your comment has been added
  21. PleaseCorrectComment: Your submitted comment had some errors, please correct and try again.
  22. HomepageTitle: Yesod Blog Demo
  23. BlogArchiveTitle: Blog Archive

Now we’re going to set up our routing table. We have four entries: a homepage, an entry list page (BlogR), an individual entry page (EntryR) and our authentication subsite. Note that BlogR and EntryR both accept GET and POST methods. The POST methods are for adding a new blog post and adding a new comment, respectively.

  1. mkYesod "Blog" [parseRoutes|
  2. / HomeR GET
  3. /blog BlogR GET POST
  4. /blog/#EntryId EntryR GET POST
  5. /auth AuthR Auth getAuth
  6. |]

Every foundation needs to be an instance of the Yesod typeclass. This is where we configure various settings.

  1. instance Yesod Blog where

The base of our application. Note that in order to make BrowserID work properly, this must be a valid URL.

  1. approot = ApprootStatic "http://localhost:3000"

Our authorization scheme. We want to have the following rules:

  • Only admins can add a new entry.

  • Only logged in users can add a new comment.

  • All other pages can be accessed by anyone.

We set up our routes in a RESTful way, where the actions that could make changes are always using a POST method. As a result, we can simply check for whether or not a request is a write request, given by the True in the second field.

First, we’ll authorize requests to add a new entry.

  1. isAuthorized BlogR True = do
  2. mauth <- maybeAuth
  3. case mauth of
  4. Nothing -> return AuthenticationRequired
  5. Just (Entity _ user)
  6. | isAdmin user -> return Authorized
  7. | otherwise -> unauthorizedI MsgNotAnAdmin

Now we’ll authorize requests to add a new comment.

  1. isAuthorized (EntryR _) True = do
  2. mauth <- maybeAuth
  3. case mauth of
  4. Nothing -> return AuthenticationRequired
  5. Just _ -> return Authorized

And for all other requests, the result is always authorized.

  1. isAuthorized _ _ = return Authorized

Where a user should be redirected to if they get an AuthenticationRequired.

  1. authRoute _ = Just (AuthR LoginR)

This is where we define our site look-and-feel. The function is given the content for the individual page, and wraps it up with a standard template.

  1. defaultLayout inside = do

Yesod encourages the get-following-post pattern, where after a POST, the user is redirected to another page. In order to allow the POST page to give the user some kind of feedback, we have the getMessage and setMessage functions. It’s a good idea to always check for pending messages in your defaultLayout function.

  1. mmsg <- getMessage

We use widgets to compose together HTML, CSS and Javascript. At the end of the day, we need to unwrap all of that into simple HTML. That’s what the widgetToPageContent function is for. We’re going to give it a widget consisting of the content we received from the individual page (inside), plus a standard CSS for all pages. We’ll use the Lucius template language to create the latter.

  1. pc <- widgetToPageContent $ do
  2. toWidget [lucius|
  3. body {
  4. width: 760px;
  5. margin: 1em auto;
  6. font-family: sans-serif;
  7. }
  8. textarea {
  9. width: 400px;
  10. height: 200px;
  11. }
  12. #message {
  13. color: #900;
  14. }
  15. |]
  16. inside

And finally we’ll use a new Hamlet template to wrap up the individual components (title, head data and body data) into the final output.

  1. withUrlRenderer [hamlet|
  2. $doctype 5
  3. <html>
  4. <head>
  5. <title>#{pageTitle pc}
  6. ^{pageHead pc}
  7. <body>
  8. $maybe msg <- mmsg
  9. <div #message>#{msg}
  10. ^{pageBody pc}
  11. |]

This is a simple function to check if a user is the admin. In a real application, we would likely store the admin bit in the database itself, or check with some external system. For now, I’ve just hard-coded my own email address.

  1. isAdmin :: User -> Bool
  2. isAdmin user = userEmail user == "[email protected]"

In order to access the database, we need to create a YesodPersist instance, which says which backend we’re using and how to run an action.

  1. instance YesodPersist Blog where
  2. type YesodPersistBackend Blog = SqlBackend
  3. runDB f = do
  4. master <- getYesod
  5. let pool = connPool master
  6. runSqlPool f pool

This is a convenience synonym. It is defined automatically for you in the scaffolding.

  1. type Form x = Html -> MForm Handler (FormResult x, Widget)

In order to use yesod-form and yesod-auth, we need an instance of RenderMessage for FormMessage. This allows us to control the i18n of individual form messages.

  1. instance RenderMessage Blog FormMessage where
  2. renderMessage _ _ = defaultFormMessage

In order to use the built-in nic HTML editor, we need this instance. We just take the default values, which use a CDN-hosted version of Nic.

  1. instance YesodNic Blog

In order to use yesod-auth, we need a YesodAuth instance.

  1. instance YesodAuth Blog where
  2. type AuthId Blog = UserId
  3. loginDest _ = HomeR
  4. logoutDest _ = HomeR

We’ll use external OpenId providers to authenticate our users and request email addresses to use as user id. This makes it easy to switch to other systems in the future, locally authenticated email addresses (also included with yesod-auth).

  1. authPlugins _ = [authOpenId Claimed
  2. [ ("openid.ns.ax", "http://openid.net/srv/ax/1.0")
  3. , ("openid.ax.mode", "fetch_request")
  4. , ("openid.ax.type.email",
  5. "http://axschema.org/contact/email")
  6. , ("openid.ax.required", "email")
  7. ]
  8. ]

This function takes someone’s login credentials (including his/her email address) and gives back a UserId.

  1. getAuthId creds =
  2. -- Key name for email value may vary between providers
  3. let emailKey = "openid.ax.value.email" in
  4. case lookup emailKey (credsExtra creds) of
  5. Just email -> do
  6. res <- liftHandler $ runDB $ insertBy (User email)
  7. return $ Just $ either entityKey id res
  8. Nothing -> return Nothing

We also need to provide a YesodAuthPersist instance to work with Persistent.

  1. instance YesodAuthPersist Blog

Homepage handler. The one important detail here is our usage of setTitleI, which allows us to use i18n messages for the title. We also use this message with a _{Msg…} interpolation in Hamlet.

  1. getHomeR :: Handler Html
  2. getHomeR = defaultLayout $ do
  3. setTitleI MsgHomepageTitle
  4. [whamlet|
  5. <p>_{MsgWelcomeHomepage}
  6. <p>
  7. <a href=@{BlogR}>_{MsgSeeArchive}
  8. |]

Define a form for adding new entries. We want the user to provide the title and content, and then fill in the post date automatically via getCurrentTime.

Note that slightly strange lift (liftIO getCurrentTime) manner of running an IO action. The reason is that applicative forms are not monads, and therefore cannot be instances of MonadIO. Instead, we use lift to run the action in the underlying Handler monad, and liftIO to convert the IO action into a Handler action.

  1. entryForm :: Form Entry
  2. entryForm = renderDivs $ Entry
  3. <$> areq textField (fieldSettingsLabel MsgNewEntryTitle) Nothing
  4. <*> lift (liftIO getCurrentTime)
  5. <*> areq nicHtmlField (fieldSettingsLabel MsgNewEntryContent) Nothing

Get the list of all blog entries, and present an admin with a form to create a new entry.

  1. getBlogR :: Handler Html
  2. getBlogR = do
  3. muser <- maybeAuth
  4. entries <- runDB $ selectList [] [Desc EntryPosted]
  5. (entryWidget, enctype) <- generateFormPost entryForm
  6. defaultLayout $ do
  7. setTitleI MsgBlogArchiveTitle
  8. [whamlet|
  9. $if null entries
  10. <p>_{MsgNoEntries}
  11. $else
  12. <ul>
  13. $forall Entity entryId entry <- entries
  14. <li>
  15. <a href=@{EntryR entryId}>#{entryTitle entry}

We have three possibilities: the user is logged in as an admin, the user is logged in and is not an admin, and the user is not logged in. In the first case, we should display the entry form. In the second, we’ll do nothing. In the third, we’ll provide a login link.

  1. $maybe Entity _ user <- muser
  2. $if isAdmin user
  3. <form method=post enctype=#{enctype}>
  4. ^{entryWidget}
  5. <div>
  6. <input type=submit value=_{MsgNewEntry}>
  7. $nothing
  8. <p>
  9. <a href=@{AuthR LoginR}>_{MsgLoginToPost}
  10. |]

Process an incoming entry addition. We don’t do any permissions checking, since isAuthorized handles it for us. If the form submission was valid, we add the entry to the database and redirect to the new entry. Otherwise, we ask the user to try again.

  1. postBlogR :: Handler Html
  2. postBlogR = do
  3. ((res, entryWidget), enctype) <- runFormPost entryForm
  4. case res of
  5. FormSuccess entry -> do
  6. entryId <- runDB $ insert entry
  7. setMessageI $ MsgEntryCreated $ entryTitle entry
  8. redirect $ EntryR entryId
  9. _ -> defaultLayout $ do
  10. setTitleI MsgPleaseCorrectEntry
  11. [whamlet|
  12. <form method=post enctype=#{enctype}>
  13. ^{entryWidget}
  14. <div>
  15. <input type=submit value=_{MsgNewEntry}>
  16. |]

A form for comments, very similar to our entryForm above. It takes the EntryId of the entry the comment is attached to. By using pure, we embed this value in the resulting Comment output, without having it appear in the generated HTML.

  1. commentForm :: EntryId -> Form Comment
  2. commentForm entryId = renderDivs $ Comment
  3. <$> pure entryId
  4. <*> lift (liftIO getCurrentTime)
  5. <*> lift requireAuthId
  6. <*> areq textField (fieldSettingsLabel MsgCommentName) Nothing
  7. <*> areq textareaField (fieldSettingsLabel MsgCommentText) Nothing

Show an individual entry, comments, and an add comment form if the user is logged in.

  1. getEntryR :: EntryId -> Handler Html
  2. getEntryR entryId = do
  3. (entry, comments) <- runDB $ do
  4. entry <- get404 entryId
  5. comments <- selectList [CommentEntry ==. entryId] [Asc CommentPosted]
  6. return (entry, map entityVal comments)
  7. muser <- maybeAuth
  8. (commentWidget, enctype) <-
  9. generateFormPost (commentForm entryId)
  10. defaultLayout $ do
  11. setTitleI $ MsgEntryTitle $ entryTitle entry
  12. [whamlet|
  13. <h1>#{entryTitle entry}
  14. <article>#{entryContent entry}
  15. <section .comments>
  16. <h1>_{MsgCommentsHeading}
  17. $if null comments
  18. <p>_{MsgNoComments}
  19. $else
  20. $forall Comment _entry posted _user name text <- comments
  21. <div .comment>
  22. <span .by>#{name}
  23. <span .at>#{show posted}
  24. <div .content>#{text}
  25. <section>
  26. <h1>_{MsgAddCommentHeading}
  27. $maybe _ <- muser
  28. <form method=post enctype=#{enctype}>
  29. ^{commentWidget}
  30. <div>
  31. <input type=submit value=_{MsgAddCommentButton}>
  32. $nothing
  33. <p>
  34. <a href=@{AuthR LoginR}>_{MsgLoginToComment}
  35. |]

Receive an incoming comment submission.

  1. postEntryR :: EntryId -> Handler Html
  2. postEntryR entryId = do
  3. ((res, commentWidget), enctype) <-
  4. runFormPost (commentForm entryId)
  5. case res of
  6. FormSuccess comment -> do
  7. _ <- runDB $ insert comment
  8. setMessageI MsgCommentAdded
  9. redirect $ EntryR entryId
  10. _ -> defaultLayout $ do
  11. setTitleI MsgPleaseCorrectComment
  12. [whamlet|
  13. <form method=post enctype=#{enctype}>
  14. ^{commentWidget}
  15. <div>
  16. <input type=submit value=_{MsgAddCommentButton}>
  17. |]

Finally our main function.

  1. main :: IO ()
  2. main = do
  3. pool <- runStdoutLoggingT $ createSqlitePool "blog.db3" 10 -- create a new pool
  4. -- perform any necessary migration
  5. runSqlPersistMPool (runMigration migrateAll) pool
  6. manager <- newManager tlsManagerSettings -- create a new HTTP manager
  7. warp 3000 $ Blog pool manager -- start our server