chore(auth): added function for user queries to auth servers

This commit is contained in:
David Mosbach 2024-01-29 21:34:39 +00:00
parent 2763d2012a
commit 5a023a9e32
2 changed files with 39 additions and 5 deletions

View File

@ -337,7 +337,7 @@ makeFoundation appSettings''@AppSettings{..} = do
return . uncurry p $ fromJust mArgs
appAuthPlugins <- liftIO $ sequence [
return oauth2MockServer
(oauth2MockServer . fromJust) <$> lookupEnv "OAUTH2_SERVER_PORT"
, loadPlugin (oauth2AzureADv2 tenantID) "AZURE_ADV2"
]

View File

@ -6,13 +6,19 @@
module Auth.OAuth2
( AzureUserException(..)
, azurePluginName
, oauth2MockServer
, mockPluginName
, queryOauth2User
) where
import Data.Text
import Import.NoFoundation
import Import.NoFoundation hiding (unpack)
import Network.HTTP.Simple (httpJSONEither, getResponseBody, JSONException)
import System.Environment (lookupEnv)
import Yesod.Auth.OAuth2
import Yesod.Auth.OAuth2.Prelude
@ -25,6 +31,9 @@ data AzureUserException = AzureUserError
instance Exception AzureUserException
azurePluginName :: Text
azurePluginName = "azureadv2"
----------------------------------------
---- OAuth2 development auth plugin ----
----------------------------------------
@ -37,8 +46,8 @@ instance FromJSON UserID where
parseJSON = withObject "UserID" $ \o ->
UserID <$> o .: "id"
oauth2MockServer :: YesodAuth m => AuthPlugin m
oauth2MockServer =
oauth2MockServer :: YesodAuth m => String -> AuthPlugin m
oauth2MockServer port =
let oa = OAuth2
{ oauth2ClientId = "42"
, oauth2ClientSecret = Just "shhh"
@ -46,7 +55,7 @@ oauth2MockServer =
, oauth2TokenEndpoint = fromString $ mockServerURL <> "/token"
, oauth2RedirectUri = Nothing
}
mockServerURL = "http://localhost:9443"
mockServerURL = "http://localhost:" <> fromString port
profileSrc = fromString $ mockServerURL <> "/users/me"
in authOAuth2 mockPluginName oa $ \manager token -> do
(UserID userID, userResponse) <- authGetProfile mockPluginName manager token profileSrc
@ -56,4 +65,29 @@ oauth2MockServer =
, credsExtra = setExtra token userResponse
}
----------------------
---- User Queries ----
----------------------
data UserData = UD
instance FromJSON UserData where
parseJSON _ = pure UD
queryOauth2User :: forall m . (MonadIO m, MonadThrow m)
=> Text
-> Text
-> m (Either JSONException UserData)
queryOauth2User authPlugin userID = do
baseUrl <- liftIO mkBaseUrl
req <- parseRequest $ "GET " ++ baseUrl ++ unpack userID
-- TODO get new token & put token in auth header
getResponseBody <$> httpJSONEither @m @UserData req
where
mkBaseUrl :: IO String
mkBaseUrl
| authPlugin == azurePluginName = return "https://graph.microsoft.com/v1.0/users/"
| authPlugin == mockPluginName = do
Just port <- lookupEnv "OAUTH2_SERVER_PORT"
return $ "http://localhost:" ++ port ++ "/users/query?id="
| otherwise = fail $ unpack authPlugin