Skip to content

Instantly share code, notes, and snippets.

@xuxucode
Created November 23, 2016 02:13
Show Gist options
  • Save xuxucode/bf88e559003a8fa5f1ce974cc4742d5d to your computer and use it in GitHub Desktop.
Save xuxucode/bf88e559003a8fa5f1ce974cc4742d5d to your computer and use it in GitHub Desktop.
Login
module Login exposing (..)
import Html exposing (Html, div, p, input, button, text)
import Html.Attributes exposing (type_, name, value, placeholder)
import Html.Events exposing (onInput, onClick)
import Http
import Json.Decode as Json
import Json.Decode.Pipeline exposing (decode, required)
import Base64
main =
Html.program
{ init = init
, update = update
, subscriptions = \_ -> Sub.none
, view = view
}
-- MODULE
type alias AuthToken =
{ type_ : String -- TODO: type is a keyword
, access_token : String
, refresh_token : String
, expires_in : Int
}
-- token : AuthToken
type alias Model =
{ name : String
, pass : String
, authToken : AuthToken
}
init : (Model, Cmd msg)
init =
(Model "" "" (AuthToken "" "" "" 0), Cmd.none)
-- UPDATE
type Msg
= EnterName String
| EnterPass String
| Login
| TokenResult (Result Http.Error AuthToken)
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
EnterName name ->
{ model | name = name } ! []
EnterPass pass ->
{ model | pass = pass } ! []
Login ->
model ! [ getToken model ]
TokenResult (Ok token) ->
let
test = Debug.log "token result" (toString token)
in
{ model | authToken = token } ! []
TokenResult (Err _) ->
Debug.crash "eeeeeeeeeeee" -- TODO: Failed case
-- getToken : { name : String, pass : String } -> Cmd Msg
getToken { name, pass } =
let
basic =
Base64.encode (name ++ ":" ++ pass)
auth =
case basic of
Ok value ->
value
_ ->
Debug.crash "Never happened" -- TODO: case never happened
url =
"https://live-hedley-elm.pantheonsite.io/api/login-token"
tokenDecoder : Json.Decoder AuthToken
tokenDecoder =
decode AuthToken
|> required "type" Json.string
|> required "access_token" Json.string
|> required "refresh_token" Json.string
|> required "expires_in" Json.int
params =
{ method = "GET"
, headers = [ Http.header "Authorization" ("Basic " ++ auth) ]
, url = url
, body = Http.emptyBody
, expect = Http.expectJson tokenDecoder
, timeout = Nothing
, withCredentials = False
}
in
Http.send TokenResult <|
Http.request params
-- VIEW
view : Model -> Html Msg
view model =
div
[]
[ p
[]
[ input
[ type_ "text"
, name "name"
, placeholder "Name"
, value model.name
, onInput EnterName
]
[]
]
, p
[]
[ input
[ type_ "password"
, name "pass"
, placeholder "Password"
, value model.pass
, onInput EnterPass
]
[]
]
, p
[]
[ button
[ onClick Login
]
[ text "Login" ]
]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment