{-# LANGUAGE OverloadedStrings          #-}
{-# LANGUAGE RecordWildCards            #-}
{-# LANGUAGE TemplateHaskell            #-}

module Session (
  SiteUser(..)
, defaultClientSessionBackend
, loadClientSession
, loadSiteUser
) where


import qualified Data.Aeson as J
import           Data.Aeson.TH
import qualified Data.ByteString.Lazy as LB
import qualified Data.Map as Map
import           Data.Text (Text)
import           Network.Wai (Request)
import           Yesod.Core (defaultClientSessionBackend)
import           Yesod.Core.Types (SessionBackend(..), SessionMap)


data SiteUser = SiteUser {
    siteUserId :: Text
  , siteUserGroups :: [Text]
  } deriving (Eq, Show)

$(deriveJSON defaultOptions { fieldLabelModifier = drop 8 } ''SiteUser)

-- | Loads SiteUser from session
loadSiteUser:: SessionBackend
            -> Request
            -> IO (Maybe SiteUser)
loadSiteUser sb r = do
  sm <- loadClientSession sb r
  return $ do bytes <- Map.lookup "_ID" sm
              J.decode $ LB.fromStrict bytes


-- | Wrapper around Yesod's loadClientSession.
-- Read only session for request authorization only.
loadClientSession:: SessionBackend
                 -> Request
                 -> IO SessionMap
loadClientSession SessionBackend{..} r = do
  (s, _) <- sbLoadSession r
  return s

