elm-pages-v3-beta/examples/pokedex/app/Route/BasicAuth.elm

134 lines
3.2 KiB
Elm
Raw Normal View History

2022-05-03 21:51:32 +03:00
module Route.BasicAuth exposing (ActionData, Data, Model, Msg, route)
import Base64
import DataSource exposing (DataSource)
2022-03-29 21:48:04 +03:00
import ErrorPage exposing (ErrorPage)
import Head
import Html exposing (div, text)
import Pages.Msg
import Pages.PageUrl exposing (PageUrl)
2022-03-05 20:50:01 +03:00
import RouteBuilder exposing (StatelessRoute, StaticPayload)
import Server.Request as Request exposing (Parser)
import Server.Response as Response exposing (Response)
import Shared
import View exposing (View)
type alias Model =
{}
type alias Msg =
()
type alias RouteParams =
{}
2022-05-03 21:51:32 +03:00
route : StatelessRoute RouteParams Data ActionData
route =
2022-03-05 20:50:01 +03:00
RouteBuilder.serverRender
{ head = head
, data = data
2022-05-03 21:51:32 +03:00
, action = \_ -> Request.skip "No action"
}
2022-03-05 20:50:01 +03:00
|> RouteBuilder.buildNoState { view = view }
type alias Data =
{ greeting : String
}
2022-05-03 21:51:32 +03:00
type alias ActionData =
{}
2022-03-29 21:48:04 +03:00
data : RouteParams -> Parser (DataSource (Response Data ErrorPage))
data routeParams =
withBasicAuth
(\{ username, password } ->
(username == "asdf" && password == "qwer")
|> DataSource.succeed
)
(Data "Login success!"
|> Response.render
|> DataSource.succeed
)
head :
2022-05-03 21:51:32 +03:00
StaticPayload Data ActionData RouteParams
-> List Head.Tag
head static =
[]
view :
Maybe PageUrl
-> Shared.Model
2022-05-03 21:51:32 +03:00
-> StaticPayload Data ActionData RouteParams
-> View (Pages.Msg.Msg Msg)
view maybeUrl sharedModel static =
{ title = "Basic Auth Test"
, body =
[ text "Basic Auth Test"
, div []
[ text static.data.greeting
]
]
}
parseAuth : String -> Maybe { username : String, password : String }
parseAuth base64Auth =
case
base64Auth
|> String.dropLeft 6
|> Base64.toString
|> Maybe.map (String.split ":")
of
Just [ username, password ] ->
Just
{ username = username
, password = password
}
_ ->
Nothing
withBasicAuth :
({ username : String, password : String } -> DataSource Bool)
2022-03-29 21:48:04 +03:00
-> DataSource (Response data ErrorPage)
-> Parser (DataSource (Response data ErrorPage))
withBasicAuth checkAuth successResponse =
2022-03-05 19:48:46 +03:00
Request.optionalHeader "authorization"
|> Request.map
(\base64Auth ->
case base64Auth |> Maybe.andThen parseAuth of
Just userPass ->
checkAuth userPass
|> DataSource.andThen
(\authSucceeded ->
if authSucceeded then
successResponse
else
requireBasicAuth |> DataSource.succeed
)
Nothing ->
requireBasicAuth
|> DataSource.succeed
)
2022-03-29 21:48:04 +03:00
requireBasicAuth : Response data ErrorPage
requireBasicAuth =
Response.emptyBody
|> Response.withStatusCode 401
|> Response.withHeader "WWW-Authenticate" "Basic"
2022-03-29 21:48:04 +03:00
|> Response.mapError never