Skip to content

Commit

Permalink
Add simple authentication helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
s9gf4ult committed Mar 24, 2015
1 parent e64773c commit eb6eda7
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
45 changes: 45 additions & 0 deletions yesod-core/Yesod/Core/Authentication.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{-# LANGUAGE OverloadedStrings #-}
module Yesod.Core.Authentication where

import Data.ByteString ( ByteString )
import Data.ByteString.Base64 ( decodeLenient )
import Data.Char ( toLower, isSpace )
import Data.Text ( Text )
import Yesod.Core.Class.Handler
import Yesod.Core.Handler

import qualified Data.ByteString.Char8 as BC
import qualified Data.Text as T
import qualified Data.Text.Encoding as T

-- | Extract basic authentication data from __Authorization__ header
-- value
extractBasicAuth :: ByteString -> Maybe (Text, Text)
extractBasicAuth bs =
let (atype, val) = BC.break isSpace bs in
case (BC.map toLower atype, BC.drop 1 val) of
("basic", payload) -> Just $ extractBasic payload
_ -> Nothing
where
extractBasic :: ByteString -> (Text, Text)
extractBasic payload = fmap (T.drop 1)
. T.breakOn ":"
. T.decodeUtf8
$ decodeLenient payload

-- | Extract bearer authentication data from __Authorization__ header
-- value
extractBearerAuth :: ByteString -> Maybe Text
extractBearerAuth bs = do
let (atype, token) = BC.break isSpace bs
if BC.map toLower atype == "bearer"
then Just $ T.decodeUtf8 $ BC.drop 1 token
else Nothing

lookupBasicAuth :: (MonadHandler m) => m (Maybe (Text, Text))
lookupBasicAuth = fmap (>>= extractBasicAuth)
(lookupHeader "Authorization")

lookupBearerAuth :: (MonadHandler m) => m (Maybe Text)
lookupBearerAuth = fmap (>>= extractBearerAuth)
(lookupHeader "Authorization")
2 changes: 2 additions & 0 deletions yesod-core/yesod-core.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ library
, wai >= 3.0
, wai-extra >= 3.0
, bytestring >= 0.9.1.4
, base64-bytestring
, text >= 0.7
, template-haskell
, path-pieces >= 0.1.2 && < 0.2
Expand Down Expand Up @@ -70,6 +71,7 @@ library
, auto-update

exposed-modules: Yesod.Core
Yesod.Core.Authentication
Yesod.Core.Content
Yesod.Core.Dispatch
Yesod.Core.Handler
Expand Down

0 comments on commit eb6eda7

Please sign in to comment.