Helper functions for working with Jwt tokens and authenticated CRUD APIs.
This package provides functions for reading tokens, and for using them to make authenticated Http requests.
Checks whether a token has expired, and returns True or False, or any error that occurred while decoding the token.
Checks a token for Expiry.
createRequest creates a Http.Request with the token added to the headers, and
sets the withCredentials field to True.
createRequestObject creates the data structure expected by Http.Request. It is broken out here so that users can change the expect part in the event that one of the REST apis does not return Json.
send replaces Http.send. On receipt of a 401 error, it returns a Jwt.Unauthorized.
sendCheckExpired is similar to send but, on receiving a 401, it carries out a further check to
determine whether the token has expired.
get is a replacement for Http.get that returns a Http.Request with the token
attached to the headers.
getData : String -> Cmd Msg
getData token =
Jwt.get token "/api/data" dataDecoder
|> Jwt.send DataResultpost is a replacement for Http.post that returns a Http.Request with the token
attached to the headers.
** Note that is important to use jsonBody to ensure that the 'application/json' is added to the headers **
postContent : Token -> Json.Decoder a -> E.Value -> String -> Request a
postContent token dec value url =
Jwt.post token url (Http.jsonBody value) (phoenixDecoder dec)
|> Jwt.send ContentResultput returns a PUT Http.Request with the token attached to the headers.
delete returns a DELETE Http.Request with the token attached to the headers.
The following errors are modeled
Examines a 401 Unauthorized reponse, and converts the error to TokenExpired when that is the case.
getAuth : String -> String -> Json.Decoder a -> Task Never (Result JwtError a)
getAuth token url dec =
createRequest "GET" token url Http.emptyBody dec
|> toTask
|> Task.map Result.Ok
|> Task.onError (promote401 token)Takes an Http.Error. If it is a 401 then it checks for token expiry.
authenticate creates an Http.Request based on login credentials.
submitCredentials : Model -> Cmd Msg
submitCredentials model =
E.object
[ ("username", E.string model.uname)
, ("password", E.string model.pword)
]
|> authenticate "/sessions" tokenStringDecoder
decodeToken parses the token, checking that it meets the Jwt standards.
In the event of success,
decodeTokenreturns an Elm record structure using the JSON Decoder.