-- SPDX-FileCopyrightText: 2024 UniWorX Systems -- SPDX-FileContributor: David Mosbach -- -- SPDX-License-Identifier: AGPL-3.0-or-later {-# Language OverloadedStrings, MultiParamTypeClasses, FlexibleInstances, QuasiQuotes #-} module LoginForm ( HTML(..) , Html , loginPage , logoutPage ) where import Prelude hiding (head) import Data.Aeson (encode) import Data.String (IsString(..)) import Data.Text (Text, unpack) import qualified Data.Map as M import qualified Data.String.Interpolate as I import GHC.Data.Maybe (whenIsJust) import Network.HTTP.Media ((//), (/:)) import Servant.API -- import Text.Blaze import Text.Blaze.Html.Renderer.Utf8 (renderHtml) import Text.Blaze.Html5 import qualified Text.Blaze.Html5.Attributes as A data HTML instance Accept HTML where contentType _ = "text" // "html" /: ("charset", "utf-8") instance MimeRender HTML Html where mimeRender _ = renderHtml loginPage :: String -> M.Map Text Text -> Html loginPage uri headers = docTypeHtml $ head' >> body' where headers' = encode headers formID = "loginForm" :: String emailID = "email" :: String buttonID = "loginButton" :: String head' = head $ do meta ! A.charset "UTF-8" meta ! A.name "viewport" ! A.content "width=device-width, initial-scale=1.0" title "UniWorX Oauth2 Mock Server" body' = body $ do h1 "UniWorX Oauth2 Mock Server" form ! A.id (fromString formID) ! A.autocomplete "on" $ do label ! A.for "email" $ "User" input ! A.type_ "email" ! A.name "email" ! A.id (fromString emailID) ! A.autocomplete "email" button ! A.type_ "button" ! A.id (fromString buttonID) $ "Login" script $ [I.i| #{buttonID}.onclick = async (e) => { const headers = new Headers(#{headers'}); const formData = new FormData(#{formID}); const creds = formData.get('#{emailID}') + ':' + ''; headers.append('Authorization', btoa(creds)); //alert(creds); e.preventDefault(); fetch('#{uri}', { method: 'GET', headers: headers }) .then(response => response.text()) .then(url => window.location.replace(url.substring(1, url.length - 1))); // Response.redirect(url); }; |] logoutPage :: Maybe Text -> Html logoutPage mUri = docTypeHtml $ head' >> body' where head' = head $ do meta ! A.charset "UTF-8" meta ! A.name "viewport" ! A.content "width=device-width, initial-scale=1.0" title "UniWorX Oauth2 Mock Server" body' = body $ do h1 "UniWorX Oauth2 Mock Server" p "Logout successful." whenIsJust mUri $ \uri -> do a ! A.href (fromString $ unpack uri) $ "Continue" script $ [I.i| setTimeout(_ => window.location.replace('#{uri}'), 2000); |]