diff --git a/package.yaml b/package.yaml index 972bddb..5c72468 100644 --- a/package.yaml +++ b/package.yaml @@ -26,6 +26,7 @@ library: - http-types >=0.8 && <0.10 - microlens - random + - safe - safe-exceptions - text >=0.7 && <2.0 - transformers >=0.2.2 && <0.6 diff --git a/src/Yesod/Auth/OAuth2.hs b/src/Yesod/Auth/OAuth2.hs index 0c44225..2b45263 100644 --- a/src/Yesod/Auth/OAuth2.hs +++ b/src/Yesod/Auth/OAuth2.hs @@ -16,11 +16,20 @@ module Yesod.Auth.OAuth2 , oauth2Url , authOAuth2 , authOAuth2Widget + + -- * Reading our @'credsExtra'@ keys + , getAccessToken + , getUserResponseJSON + , getUserResponse ) where +import Data.Aeson (FromJSON, eitherDecode) +import Data.ByteString.Lazy (ByteString, fromStrict) import Data.Text (Text) +import Data.Text.Encoding (encodeUtf8) import Network.HTTP.Conduit (Manager) import Network.OAuth.OAuth2 +import Safe (fromJustNote) import Yesod.Auth import Yesod.Auth.OAuth2.Dispatch import Yesod.Core.Widget @@ -51,3 +60,29 @@ authOAuth2Widget widget name oauth getCreds = AuthPlugin name (dispatchAuthRequest name oauth getCreds) login where login tm = [whamlet|^{widget}|] + +-- | Read from the values set via @'setExtra'@ +-- +-- This is unsafe. +-- +getAccessToken :: Creds m -> AccessToken +getAccessToken = AccessToken + . fromJustNote "yesod-auth-oauth2 bug: credsExtra without accessToken" + . lookup "accessToken" . credsExtra + +-- | Read from the values set via @'setExtra'@ +-- +-- This is unsafe. +-- +getUserResponseJSON :: Creds m -> ByteString +getUserResponseJSON = fromStrict . encodeUtf8 + . fromJustNote "yesod-auth-oauth2 bug: credsExtra without userResponseJSON" + . lookup "userResponseJSON" . credsExtra + +-- | Read from the values set via @'setExtra'@ +-- +-- This is unsafe if the key is missing, but safe with respect to parsing +-- errors. +-- +getUserResponse :: FromJSON a => Creds m -> Either String a +getUserResponse = eitherDecode . getUserResponseJSON