Skip to content

Instantly share code, notes, and snippets.

@dpwiz
Last active August 31, 2016 14:28
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dpwiz/3121322 to your computer and use it in GitHub Desktop.
Save dpwiz/3121322 to your computer and use it in GitHub Desktop.
Check Basic HTTP Authentication in Scotty
main :: IO ()
main = scotty 3000 app
app :: ScottyM ()
app = do
rcon <- liftIO $ R.connect R.defaultConnectInfo {R.connectPort = R.UnixSocket "redis.sock"}
get "/favicon.ico" $ html "ಠ_ಠ"
get "/:method" $ do
r <- request
auth <- liftIO $ auth r rcon
unless (isJust auth) next
liftIO someCode
get "/:method" $ do
status unauthorized401
header "WWW-Authenticate" "Basic realm=\"Incoming\""
html "<h1>Authentication required.</h1>"
auth :: Request -> R.Connection -> IO (Maybe ByteString)
auth (Request {requestHeaders=h}) rcon = do
case [v | (k, v) <- h, k == "Authorization" ] of
[value] -> R.runRedis rcon $ check (decode value)
_ -> return Nothing
where
decode = BS.split ':' . decodeLenient . head . drop 1 . BS.split ' '
check [login, pwd] = FA.checkAuth login pwd
@dpwiz
Copy link
Author

dpwiz commented Apr 14, 2016

The times have changed since the gist. Please check out the more recent approach using middleware from wai-extra: https://ro-che.info/articles/2016-04-14-scotty-http-basic-auth

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment