-
Notifications
You must be signed in to change notification settings - Fork 368
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters