Safe authorization

This commit is contained in:
VyacheslavHashov 2017-02-09 11:09:26 +03:00
parent 1bb7f44b10
commit ded4e60df0

View File

@ -8,6 +8,7 @@ import Control.Monad
import Data.Traversable import Data.Traversable
import Data.Foldable import Data.Foldable
import Control.Applicative import Control.Applicative
import Control.Exception
import Data.IORef import Data.IORef
import Data.Monoid import Data.Monoid
import Control.Concurrent (forkIO, killThread, ThreadId, threadDelay) import Control.Concurrent (forkIO, killThread, ThreadId, threadDelay)
@ -88,11 +89,15 @@ connectWith
-> ServerMessageFilter -> ServerMessageFilter
-> IO (Either Error Connection) -> IO (Either Error Connection)
connectWith settings msgFilter = connectWith settings msgFilter =
createRawConnection settings >>= bracketOnError
either throwErrorInIO (\rawConn -> (createRawConnection settings)
authorize rawConn settings >>= (either throwErrorInIO rClose)
either throwErrorInIO (\params -> (either throwErrorInIO performAuth)
Right <$> buildConnection rawConn params msgFilter)) where
performAuth rawConn = authorize rawConn settings >>= either
-- We should close connection on an authorization failure
(\e -> rClose rawConn >> throwErrorInIO e)
(\params -> Right <$> buildConnection rawConn params msgFilter)
-- | Authorizes on the server and reads connection parameters. -- | Authorizes on the server and reads connection parameters.
authorize authorize
@ -108,8 +113,8 @@ authorize rawConn settings = do
readAuthResponse = do readAuthResponse = do
-- 4096 should be enough for the whole response from a server at -- 4096 should be enough for the whole response from a server at
-- the startup phase. -- the startup phase.
r <- rReceive rawConn 4096 resp <- rReceive rawConn 4096
case runDecode decodeAuthResponse r of case runDecode decodeAuthResponse resp of
Right (rest, r) -> case r of Right (rest, r) -> case r of
AuthenticationOk -> AuthenticationOk ->
pure $ parseParameters rest pure $ parseParameters rest