aboutsummaryrefslogtreecommitdiff
path: root/src/server/LoginSession.hs
blob: 3897b4cdb8eac27d72a311e8797bdc2eb573237e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
{-# LANGUAGE OverloadedStrings #-}

module LoginSession
  ( put
  , get
  , delete
  ) where

import Web.Scotty (ActionM)
import Cookie (setSimpleCookie, getCookie, deleteCookie)
import qualified Web.ClientSession as CS

import Control.Monad.IO.Class (liftIO)

import Data.Text (Text)
import qualified Data.Text.Encoding as TE

sessionName :: Text
sessionName = "SESSION"

sessionKeyFile :: FilePath
sessionKeyFile = "sessionKey"

put :: Text -> ActionM ()
put value = do
  encrypted <- liftIO $ encrypt value
  setSimpleCookie sessionName encrypted

encrypt :: Text -> IO Text
encrypt value = do
  iv <- CS.randomIV
  key <- CS.getKey sessionKeyFile
  return . TE.decodeUtf8 $ CS.encrypt key iv (TE.encodeUtf8 value)

get :: ActionM (Maybe Text)
get = do
  maybeEncrypted <- getCookie sessionName
  case maybeEncrypted of
    Just encrypted ->
      liftIO $ decrypt encrypted
    Nothing ->
      return Nothing

decrypt :: Text -> IO (Maybe Text)
decrypt encrypted = do
  key <- CS.getKey sessionKeyFile
  let decrypted = TE.decodeUtf8 <$> CS.decrypt key (TE.encodeUtf8 encrypted)
  return decrypted

delete :: ActionM ()
delete = deleteCookie sessionName