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.
Note: This function assumes that the expiry was set in seconds and thus multiplies by 1000 to compare with Javascript time (in milliseconds). You may need to write a custom version if your server-side Jwt library works differently.
createRequest creates a Http.Request with the token added to the headers, and
sets the withCredentials field to True.
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.
put 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.
JwtErrors and Http.Error handlingThe 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 chekcs for expirey.
Checks a token for expirey.
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)
]
|> authenticateRequest "/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.