{-# LANGUAGE OverloadedStrings #-} module Secure ( loggedAction , getUserFromToken ) where import Control.Monad.IO.Class (liftIO) import Data.Text (Text) import Data.Text.Lazy (fromStrict) import Network.HTTP.Types.Status (forbidden403) import Web.Scotty import Model.Message (getMessage) import Model.Query (Query) import Model.User (User) import qualified LoginSession import qualified Model.Message.Key as Key import qualified Model.Query as Query import qualified Model.SignIn as SignIn import qualified Model.User as User loggedAction :: (User -> ActionM ()) -> ActionM () loggedAction action = do maybeToken <- LoginSession.get case maybeToken of Just token -> do maybeUser <- liftIO . Query.run . getUserFromToken $ token case maybeUser of Just user -> action user Nothing -> do status forbidden403 html . fromStrict . getMessage $ Key.UnauthorizedSignIn Nothing -> do status forbidden403 html . fromStrict . getMessage $ Key.Forbidden getUserFromToken :: Text -> Query (Maybe User) getUserFromToken token = do mbSignIn <- SignIn.getSignIn token case mbSignIn of Just signIn -> User.getUser (SignIn.email signIn) Nothing -> return Nothing