Only accepting a WAI Websocket request if the user is logged in

100 Views Asked by At

I am using the wai-websockets package (version 3.0.1.1) and I would like to only open a socket if the user has already logged in. I have a piece of middleware that takes care of all the authentication issues and if the user is logged in places a User record into the Vault of the WAI request.

Is there some way to access the WAI Request from the ServerApp, or in the alternative to inspect the Request before the it starts and pass the User value in?

1

There are 1 best solutions below

0
On

The following basic structure will allow you to analyze the Request before passing control to the websockets, and allow you to pass the Request value into your ServerApp if desired:

#!/usr/bin/env stack
-- stack --resolver lts-9.3 script
{-# LANGUAGE OverloadedStrings #-}
import Network.Wai
import Network.Wai.Handler.Warp
import Network.Wai.Handler.WebSockets
import Network.HTTP.Types
import Network.WebSockets.Connection

main :: IO ()
main = run 3000 $ \req send ->
case websocketsApp defaultConnectionOptions _serverApp req of
    Nothing -> send $ responseLBS status200 [] "Websockets not supported"
    Just res -> send res